package com.tigase.serviceImpl;

import com.tigase.bean.TigaseUser;
import com.tigase.dao.JDBCDao.UserJDBCDao;
import com.tigase.dao.TigaseUserMapper;
import com.tigase.service.UserService;
import com.tigase.utils.MD5;
import com.tigase.utils.UUIDUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * Created by Mer on 2017/7/6.
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private JdbcTemplate jdbcTemplate;


    public void create(String name, Integer age) {
        jdbcTemplate.update("insert into USER(NAME, AGE) values(?, ?)", name, age);
    }


    public void deleteByName(String name) {
        jdbcTemplate.update("delete from USER where NAME = ?", name);
    }


    public Integer getAllUsers() {
        return jdbcTemplate.queryForObject("select count(1) from USER", Integer.class);
    }


    public void deleteAllUsers() {
        jdbcTemplate.update("delete from USER");
    }


    public TigaseUser registerUser(String userId) {
        String sql= "SELECT user_id,user_name,user_pass,account_status from t_user WHERE user_name = ?";

        String name=null;
        List<Map<String, Object>> names = jdbcTemplate.queryForList(sql,userId);
        TigaseUser users=new TigaseUser();
        if(names.size()>0){
            for(int i=0;i<names.size();i++){
                TigaseUser user=new TigaseUser();
                String id=(String) names.get(i).get("user_id");
                name= (String) names.get(i).get("user_name");
                String pass= (String) names.get(i).get("user_pass");
                int status= (int) names.get(i).get("account_status");
                user.setUserId(id);
                user.setUserName(name);
                user.setUserPass(pass);
                user.setAccountStatus(status);
                return user;
            }
        }
        return users;
    }


    public TigaseUser findAllByUserId(String userId) {
        return null;
    }


    public int insertUser(TigaseUser user) {

        String sql= "INSERT INTO  t_user(user_id,user_name,user_pass,online_status,create_time,account_status,user_nick) VALUES (?,?,?,?,?,?,?) ";
        String uuid= UUIDUtils.getUUID();
        String nick=null;
        if(StringUtils.isEmpty(user.getUserNick())){
            nick=user.getUserName();
        }else{
            nick=user.getUserNick();
        }
        int a= jdbcTemplate.update(sql,new Object[] {uuid,user.getUserName(), MD5.GetMD5Code(user.getUserPass()),0,new Date(),1,nick});

        return a;
    }


    public int updateUserMse(TigaseUser user) {
        return 0;
    }

}
